<?php

namespace App\Http\Controllers\Invoice;

use App\Http\Controllers\BaseController;
use App\Services\Common\CommonExcelExport;
use Illuminate\Http\Request;
use App\Http\Validate\Invoice\Invoice;
use App\Models\Invoice\Invoice as ModelInvoice;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 基础信息，开票管理
 */
class InvoiceController extends BaseController
{
    /**
     * 添加
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only([
            'custom_id',
            'company_code',
            'company_name',
            'category',
            'firm_name',
            'credit_code',
            'firm_address',
            'firm_phone_number',
            'firm_bank',
            'firm_bank_number',
            'firm_email'
        ]);
        $validate = new Invoice('add');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $data = [
            'cpid' => $cpid,
            'custom_id' => $req_data['custom_id'],
            'manger_id' => $manger_id,
            'company_code' => $req_data['company_code'],
            'company_name' => $req_data['company_name'],
            'category' => $req_data['category'],
            'firm_name' => $req_data['firm_name'],
            'credit_code' => $req_data['credit_code'],
            'firm_address' => $req_data['firm_address'],
            'firm_phone_number' => $req_data['firm_phone_number'],
            'firm_bank' => $req_data['firm_bank'],
            'firm_bank_number' => $req_data['firm_bank_number'],
            'firm_email' => $req_data['firm_email'],
            'create_at' => time(),
        ];
        ModelInvoice::create($data);
        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 详情
     */
    public function getone(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelInvoice::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '开票信息不存在']);
        }
        $one = $one->toArray();
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }

    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only([
            'id',
            'custom_id',
            'company_code',
            'company_name',
            'category',
            'firm_name',
            'credit_code',
            'firm_address',
            'firm_phone_number',
            'firm_bank',
            'firm_bank_number',
            'firm_email'
        ]);
        $validate = new Invoice('edit');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $data = [
            'cpid' => $cpid,
            'custom_id' => $req_data['custom_id'],
            'manger_id' => $manger_id,
            'company_code' => $req_data['company_code'],
            'company_name' => $req_data['company_name'],
            'category' => $req_data['category'],
            'firm_name' => $req_data['firm_name'],
            'credit_code' => $req_data['credit_code'],
            'firm_address' => $req_data['firm_address'],
            'firm_phone_number' => $req_data['firm_phone_number'],
            'firm_bank' => $req_data['firm_bank'],
            'firm_bank_number' => $req_data['firm_bank_number'],
            'firm_email' => $req_data['firm_email'],
            'update_at' => time(),
        ];
        ModelInvoice::where([['id', $req_data['id']]])->update($data);
        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelInvoice::getList($request, $memberinfo, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 提交审核 会计端审核
     * status 1待审核 2审核中 3通过 4驳回
     */
    public function dopostreview(Request $request)
    {
        $req_data = $request->only(['id', 'status']);
        $validate = new Invoice('dopostreview');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $id = $req_data['id'];
        $status = $req_data['status'];
        $info = ModelInvoice::where([['id', $id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        ModelInvoice::where([['id', $id]])->update(['status' => $status, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 模板下载
     */
    public function dodownload()
    {
        $filenmame = '/template/开票信息导入模版.xlsx';
        if (file_exists(storage_path() . $filenmame) && is_file(storage_path() . $filenmame)) {
            ob_clean();
            return response()->download(storage_path() . $filenmame);
        }
        return response()->json(['code' => '001', 'msg' => '文件不存在，下载失败'], 200);
    }

    /**
     * 上传导入，先调用uploadfile，返回地址调用该接口
     */
    public function doimport(Request $request)
    {
        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $invoice_arr = Excel::toArray(null, $file)[0];

            if (count($invoice_arr) < 2) {
                return response()->json(['code' => '001', 'msg' => '请填写开票信息'], 200);
            }

            unset($invoice_arr[0]);

            $import = [];
            foreach ($invoice_arr as $key => $invoice) {
                $import[$key]['company_code'] = $invoice[0];
                $import[$key]['company'] = $invoice[1];
                $import[$key]['company_name'] = $invoice[2];
                $import[$key]['firm_name'] = $invoice[3];
                $import[$key]['credit_code'] = $invoice[4];
                $import[$key]['firm_address'] = $invoice[5];
                $import[$key]['firm_phone_number'] = $invoice[6];
                $import[$key]['firm_bank'] = $invoice[7];
                $import[$key]['firm_bank_number'] = $invoice[8];
                $import[$key]['firm_email'] = $invoice[9];
            }

            $mangerinfo = $this->mangerinfo;
            $cpid = $mangerinfo['cpid'] ?? 0;
            $manger_id = $mangerinfo['id'] ?? 0;

            DB::beginTransaction();
            try {
                foreach ($import as $item) {
                    $data = [
                        'cpid' => $cpid,
                        'manger_id' => $manger_id,
                        'company_code' => $item['company_code'],
                        'company_name' => $item['company_name'],
                        'firm_name' => $item['firm_name'],
                        'credit_code' => $item['credit_code'],
                        'firm_address' => $item['firm_address'],
                        'firm_phone_number' => $item['firm_phone_number'],
                        'firm_bank' => $item['firm_bank'],
                        'firm_bank_number' => $item['firm_bank_number'],
                        'firm_email' => $item['firm_email'],
                        'create_at' => time(),
                    ];
                    ModelInvoice::create($data);
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getMessage()]);
            }
            return response()->json(['code' => '000', 'msg' => '操作成功'], 200);
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在'], 200);
        }
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 1;
        $list = ModelInvoice::getList($request, $memberinfo, $isgetall);

        $exceldata = [];
        $row = [
            [
                'id' => '序号',
                'company' => '往来单位',
                'company_code' => '往来单位编码',
                'company_name' => '往来单位名称',
                'firm_name' => '公司名称',
                'credit_code' => '统一信用代码',
                'firm_address' => '公司地址',
                'firm_phone_number' => '公司电话',
                'firm_bank' => '公司开户行',
                'firm_bank_number' => '公司账户',
                'firm_email' => '公司邮箱',
                'business_license' => '上传营业执照',
                'account_opening_permit' => '上传开户许可证',
                'attorney' => '上传委托书',
                'status' => '状态',
            ]
        ];
        foreach ($list['list'] as $val) {
            switch ($val['status']) {
                case 1:
                    $status = '待审核';
                    break;
                case 2:
                    $status = '审核中';
                    break;
                case 3:
                    $status = '通过';
                    break;
                case 4:
                    $status = '驳回';
                    break;
            }


            $row[] = [
                'id' => $val['id'],
                'company' => $val['company'],
                'company_code' => $val['company_code'],
                'company_name' => $val['company_name'],
                'firm_name' => $val['firm_name'],
                'credit_code' => $val['credit_code'],
                'firm_address' => $val['firm_address'],
                'firm_phone_number' => $val['firm_phone_number'],
                'firm_bank' => $val['firm_bank'],
                'firm_bank_number' => $val['firm_bank_number'],
                'firm_email' => $val['firm_email'],
                'business_license' => $val['business_license'],
                'account_opening_permit' => $val['account_opening_permit'],
                'attorney' => $val['attorney'],
                'status' => $status,
            ];
        }

        $datawith = [];
        $filename = '开票信息导出.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, $datawith), $filename);
    }
}